import React from 'react';
import { Form, Input, Tabs, Tree, Modal, Radio, Checkbox, Button, message, Row, Col, Icon } from 'antd';
import { connect } from 'dva';
import styles from "./index.less";
import { postAppUserAuth, getAllApplicationAdmin } from "@/services/user";
import { formatMessage } from 'umi-plugin-react/locale';
const { TreeNode } = Tree;
const { TabPane } = Tabs;

const DEFAULT_STATE = {
    visible: false,
    queryData: {
        search: '',
        targetId: '',
    },
    allApplications: [],
    // 选择的目录
    activeUserList: [
        { name: formatMessage({ id: 'account.authManage.authorizationAddModal.subscriber', defaultMessage: '联系人' }), id: 'AB001' },
        // { name: '甲方企业', id: 'xxx' },
    ],
    // 当前目录下的企业或用户
    userList: [
        // { name: '甲方企业', id: 'xxx', isCheck: false, isCategory: true }, // isCheck: 是否显示checkbox
        // { name: '甲方管理员', id: 'xxx', isCheck: false, isCategory: false },
    ],
    disabledSelectUserIds: [],
    selectUserIds: [],
    selectUserList: [
        // { name: '甲方管理员', id: 'xxx' },
    ]
}

class AuthorizationAddModal4App extends React.Component {
    constructor(props) {
        super(props);
        this.state = JSON.parse(JSON.stringify(DEFAULT_STATE));
    }

    componentDidMount() {
        if (this.props.onRef) {
            this.props.onRef(this);
        }
    }

    initData = () => {
        let { targetId } = this.props;
        let { queryData } = this.state;
        queryData.targetId = targetId;
        this.setState({
            visible: true,
            queryData,
            userList: [],
        }, () => this.getAuthList());
    }

    getAuthList = async () => {
        const queryData = { roleId: this.props.targetId };
        const allApplications = await getAllApplicationAdmin(queryData);
        if (!allApplications) {
            return;
        }
        const disabledSelectUserIds = [];
        allApplications.forEach((app) => {
            app.applicationUsers.forEach((user) => {
                user.originName = user.name;
                user.name = user.phone;
                user.isCategory = false;
                user.isCheck = true;
                if (user.checked === 'true') {
                    disabledSelectUserIds.push(user.id);
                }
            })
            app.id = app.applicationId;
            app.name = app.applicationName;
            app.isCheck = false;
            app.isCategory = true;
        })
        this.setState({ allApplications, userList: [...allApplications], selectUserIds: [...disabledSelectUserIds], disabledSelectUserIds });
    }

    // 返回上一级目录
    setTitleClick = row => {
        let { activeUserList, userList } = this.state;
        switch (row.id) {
            case 'AB001':
                activeUserList = activeUserList.slice(0, 1);
                activeUserList = [{ name: formatMessage({ id: 'account.authManage.authorizationAddModal.contact' }), id: 'AB001' }];
                userList = [...this.state.allApplications];
                this.setState({ activeUserList, userList });
                break;
            default:
                const ids = activeUserList.map(item => item.id);
                activeUserList = activeUserList.slice(0, ids.indexOf(row.id) + 1);
                userList = [...list[list.length - 1].applicationUsers];
                break;
        }
        this.setState({ activeUserList, userList });
    }

    // 进入下一级目录
    setClick = (row) => {
        const { activeUserList } = this.state;
        activeUserList.push(row);
        const userList = [...row.applicationUsers];
        this.setState({ activeUserList, userList });
    }
    // 搜索用户或企业
    getList = async () => {
        const { activeUserList, allApplications, queryData } = this.state;
        const current = activeUserList[activeUserList.length - 1];
        let userList;
        if (current.id === 'AB001') {
            userList = queryData.search !== ''
                ? allApplications.filter((app) => app.applicationName.includes(queryData.search)
                    || app.applicationUsers.some((user) => user.phone.includes(queryData.search)))
                : [...allApplications];
        } else {
            userList = queryData.search !== ''
                ? current.applicationUsers.filter((user) => user.phone.includes(queryData.search))
                : [...current.applicationUsers];
        }
        this.setState({ userList });
    }

    removeClick = row => {
        let { selectUserList, selectUserIds } = this.state;
        selectUserList = selectUserList.filter(item => item.id != row.id);
        selectUserIds = selectUserIds.filter(item => item != row.id);
        this.setState({ selectUserList, selectUserIds });
    }

    changeRoleName = e => {
        let { queryData } = this.state;
        queryData.search = e.target.value;
        this.setState({ queryData }, () => {
            this.getList();
        });
    }

    onClose = () => {
        this.setState(JSON.parse(JSON.stringify(DEFAULT_STATE)));
    }

    onSubmit = () => {
        const { selectUserList } = this.state;
        if (selectUserList && selectUserList.length > 0) {
            this.addRole();
        } else {
            return message.error('请选择用户');
        };
    }

    addRole = async () => {
        const { queryData, selectUserList } = this.state;
        const authData = selectUserList.map(item => ({
            relId: item.id,
            targetId: queryData.targetId,
        }));
        const res = await postAppUserAuth({ authData });
        if (res.code === 0) {
            message.success('添加成功')
            this.onClose();
            this.props.getList();
        }
    }

    onChange = row => {
        let { selectUserIds, selectUserList } = this.state;
        let list = [];
        if (selectUserIds.indexOf(row.id) > -1) {
            list = selectUserList.filter(item => item.id != row.id);
            selectUserIds = selectUserIds.filter(item => item != row.id);
        } else {
            list = [...selectUserList, { ...row }];
            selectUserIds = [...selectUserIds, row.id];
        };
        this.setState({ selectUserList: [...list], selectUserIds });
    }

    render() {
        const { visible, userList, disabledSelectUserIds, selectUserIds, selectUserList, queryData, activeUserList } = this.state;
        return (
            <Modal
                title={formatMessage({ id: 'account.authManage.authorizationAddModal4App.addRole', defaultMessage: '添加角色' })}
                visible={visible}
                width={840}
                onCancel={this.onClose}
                footer={[
                    <Button onClick={this.onClose} style={{ marginRight: 8 }}>{formatMessage({ id: 'account.authManage.authorizationAddModal.cancel', defaultMessage: '取消' })}</Button>,
                    <Button onClick={this.onSubmit} type="primary">{formatMessage({ id: 'account.authManage.authorizationAddModal.confirm', defaultMessage: '确定' })}</Button>
                ]}
            >
                <div style={{ border: '1px solid #d0d3d6', borderRadius: '8px' }} className={styles.userAuthModal}>
                    <div style={{ display: 'flex' }}>
                        <div style={{ width: 'calc(50% - 1px)', padding: '16px', borderRight: '1px solid #d0d3d6' }}>
                            <Input
                                placeholder={formatMessage({ id: 'account.authManage.authorizationAddModal4App.searchUserOrCompany', defaultMessage: '搜索用户或企业' })}
                                value={queryData.search}
                                onChange={this.changeRoleName}
                                onPressEnter={this.changeRoleName}
                                maxLength={60}
                            />
                            <div
                                style={{
                                    lineHeight: '40px',
                                    height: activeUserList && activeUserList.length > 0 ? '' : '16px',
                                    display: queryData.search != '' && queryData.search.length > 0 ? 'none' : 'block',
                                    whiteSpace: 'nowrap',
                                    overflow: 'hidden',
                                    textOverflow: 'ellipsis',
                                }}
                            >
                                <span>
                                    {activeUserList.map((item, index) => {
                                        const isContact = item.id === 'AB001';
                                        return (
                                            <span key={index}>
                                                {activeUserList.length == index + 1 ? (
                                                    <span>{isContact ? formatMessage({ id: 'account.authManage.authorizationAddModal.contact', defaultMessage: '联系人' }) : item.name}</span>
                                                ) : (
                                                    <>
                                                        <span
                                                            style={{ color: '#3E5BFF', cursor: 'pointer' }}
                                                            onClick={() => this.setTitleClick(item)}
                                                        >
                                                            {isContact ? formatMessage({ id: 'account.authManage.authorizationAddModal.contact', defaultMessage: '联系人' }) : item.name}
                                                        </span>
                                                        <Icon type="right" style={{ margin: '0 5px' }} />
                                                    </>
                                                )}
                                            </span>
                                        )
                                    })}
                                </span>
                            </div>
                            {activeUserList.length>1&&<Checkbox onChange={(e)=>{
                                if (e.target.checked) {
                                    this.setState({selectUserIds:userList.reduce((pre,item)=>{
                                        return pre.concat(item.id)
                                        },[]),selectUserList:userList.filter(item=>!(selectUserIds.indexOf(item.id) > -1))})
                                }else {
                                    this.setState({selectUserIds:[...disabledSelectUserIds],selectUserList:[]});
                                }
                            }}>{formatMessage({ id: 'account.authManage.authorizationAddModal4App.all', defaultMessage: '全选' })}</Checkbox>}
                            <Checkbox.Group
                                style={{
                                    width: 'calc(100% + 16px)',
                                    maxHeight: '490px',
                                    overflow: 'hidden auto',
                                    marginLeft: -8,
                                    marginTop: queryData.search != '' && queryData.search.length > 0 ? '16px' : '0px',
                                }}
                                value={selectUserIds}
                            >
                                <Row className={styles.userList}>
                                    {userList.map((item, index) => {
                                        return (
                                            <>
                                                {item && item.isCheck ? (
                                                    <Col span={24} className={styles.userLi} key={index}>
                                                        <Checkbox
                                                            value={item.id}
                                                            disabled={disabledSelectUserIds.indexOf(item.id) > -1}
                                                            onChange={() => this.onChange(item)}
                                                        >
                                                            {item.name}
                                                        </Checkbox>
                                                        {item.isCategory ? (
                                                            <span
                                                                style={selectUserIds.indexOf(item.id) > -1 ? {
                                                                    cursor: 'no-drop',
                                                                    color: '#D4D4D4',
                                                                } : {
                                                                    cursor: 'pointer',
                                                                }}
                                                            >
                                                                <span
                                                                    style={selectUserIds.indexOf(item.id) > -1 ? {
                                                                        cursor: 'no-drop',
                                                                        pointerEvents: 'none',
                                                                        color: '#D4D4D4',
                                                                        backgroundColor: 'unset',
                                                                    } : {
                                                                        cursor: 'pointer',
                                                                    }}
                                                                    onClick={() => this.setClick(item)}
                                                                >
                                                                    <span>{formatMessage({ id: 'account.authManage.authorizationAddModal4App.nextLevel', defaultMessage: '下级' })}</span>
                                                                    <Icon type="right" />
                                                                </span>
                                                            </span>
                                                        ) : null}
                                                    </Col>
                                                ) : (
                                                    <Col
                                                        span={24}
                                                        className={styles.userLi}
                                                        key={index}
                                                        style={{ cursor: 'pointer' }}
                                                        onClick={() => this.setClick(item)}
                                                    >
                                                        <label value={item.name} style={{ cursor: 'pointer' }}>{item.name}</label>
                                                        {item.isCategory ? (
                                                            <span>
                                                                <span>
                                                                    <span>{formatMessage({ id: 'account.authManage.authorizationAddModal4App.nextLevel', defaultMessage: '下级' })}</span>
                                                                    <Icon type="right" />
                                                                </span>
                                                            </span>
                                                        ) : null}
                                                    </Col>
                                                )}
                                            </>
                                        )
                                    })}
                                </Row>
                            </Checkbox.Group>
                        </div>
                        <div style={{ width: '50%', padding: '16px' }}>
                            <div style={{ lineHeight: '36px' }}>{formatMessage({ id: 'account.authManage.authorizationAddModal4App.selected', defaultMessage: '已选' })}：{selectUserList.length} {formatMessage({ id: 'account.authManage.authorizationAddModal4App.user', defaultMessage: '个' })}</div>
                            <ul
                                style={{
                                    padding: 0,
                                    width: '100%',
                                    maxHeight: '466px',
                                    overflow: 'hidden auto',
                                    marginLeft: -8,
                                }}
                                className={styles.selectUserList}
                            >
                                {selectUserList.map((item, index) => {
                                    return (
                                        <li className={styles.selectUserLi} key={index}>
                                            <span>{item.name}</span>
                                            <Icon type="close" onClick={() => this.removeClick(item)} />
                                        </li>
                                    )
                                })}
                            </ul>
                        </div>
                    </div>
                </div>
            </Modal>
        )
    }
}

export default connect(({ user }) => ({
    currentUser: user.currentUser,
}))(AuthorizationAddModal4App);
